'''
Created on Mar 14, 2011

@author: oabalbin
'''

import re
import subprocess
from optparse import OptionParser
def read_file(input_file_name,out_file_name):
    '''
    Just change the spaces of a line for tabs
    It is currently used to process the hapmap
    processed file, which contains spaces instead
    of tabs as field separator
    '''
    input_file = open(input_file_name)
    outfile=open(out_file_name,'w')
    
    for l in input_file:
        
        if l.startswith('#'):
            outfile.write(l)
            continue
        if l.startswith('MT'):
            fields = l.strip('\n').split('\t')
            print fields
            
            chr=fields[0].replace('MT','chrM')
            fields.pop(0)
            fields.insert(0,chr)
            outfile.write(",".join(fields).replace(',','\t')+'\n')
            continue
    
    input_file.close()

    input_file = open(input_file_name)
    for l in input_file:
        fields=l.strip('\n').split('\t')
        if l.startswith('#') or l.startswith('MT') or (re.search('random',fields[0]) is not None) or \
           (re.search('hap',fields[0]) is not None) or (re.search('PAR',fields[0]) is not None):
            continue
        
        chr="chr"+fields[0]
        fields.pop(0)
        fields.insert(0,chr)
        outfile.write(",".join(fields).replace(',','\t')+'\n')
       
    outfile.close()
    


def read_file_hp(input_file_name,out_file_name):
    '''
    Just change the spaces of a line for tabs
    It is currently used to process the hapmap
    processed file, which contains spaces instead
    of tabs as field separator
    '''
    out_file_name_tmp = out_file_name+'_tmp' 
    input_file = open(input_file_name)
    outfile=open(out_file_name,'w')
    outfiletemp=open(out_file_name_tmp,'w')
    
    for l in input_file:
        
        if l.startswith('#'):
            outfiletemp.write(l)
            continue
        if l.startswith('MT'):
            fields = l.strip('\n').split('\t')
            
            chr=fields[0].replace('MT','chrM')
            fields.pop(0)
            fields.insert(0,chr)
            outfiletemp.write(",".join(fields).replace(',','\t')+'\n')
            continue
        
        fields=l.strip('\n').split('\t')
        if (re.search('random',fields[0]) is not None) or \
           (re.search('hap',fields[0]) is not None) or (re.search('PAR',fields[0]) is not None):
            continue
        
        chr="chr"+fields[0]
        fields.pop(0)
        fields.insert(0,chr)
        outfile.write(",".join(fields).replace(',','\t')+'\n')
       
    outfile.close()
    outfiletemp.close()
    input_file.close()
    
    out_file_name_ff = out_file_name+'_ff'
    ffile=open(out_file_name_ff,'w')
    subprocess.call(['cat',out_file_name_tmp,out_file_name],stdout=ffile)
    ffile.close()


def read_file_hp2(input_file_name,out_file_name,short=False):
    '''
    Just change the spaces of a line for tabs
    It is currently used to process the hapmap
    processed file, which contains spaces instead
    of tabs as field separator
    '''
    out_file_name_tmp = out_file_name+'_tmp' 
    input_file = open(input_file_name)
    outfile=open(out_file_name,'w')
    outfiletemp=open(out_file_name_tmp,'w')
    firstsamplecol=8
    
    for l in input_file:
        
        if l.startswith('#'):
            outfiletemp.write(l)
            continue
                
        if l.startswith('MT'):
            fields = l.strip('\n').replace(',','$').split('\t')
            chr=fields[0].replace('MT','chrM')
            fields.pop(0)
            fields.insert(0,chr)
            
            if short:
                fields=fields[:firstsamplecol]
                
            oline = ",".join(fields).replace(',','\t')
            outfile.write(oline.replace('$',',')+'\n')
            continue
        
        fields=l.strip('\n').replace(',','$').split('\t')
        if (re.search('random',fields[0]) is not None) or \
           (re.search('hap',fields[0]) is not None) or (re.search('PAR',fields[0]) is not None):
            continue
        
        chr="chr"+fields[0]
        fields.pop(0)
        fields.insert(0,chr)
        if short:
            fields=fields[:firstsamplecol]
        
        oline = ",".join(fields).replace(',','\t')
        outfile.write(oline.replace('$',',')+'\n')
       
    outfile.close()
    outfiletemp.close()
    input_file.close()
    
    out_file_name_ff = out_file_name+'_ff'
    ffile=open(out_file_name_ff,'w')
    subprocess.call(['cat',out_file_name_tmp,out_file_name],stdout=ffile)
    ffile.close()
    subprocess.call(['rm',out_file_name_tmp])
    subprocess.call(['mv',out_file_name_ff, out_file_name])



if __name__ == '__main__':
        
    optionparser = OptionParser("usage: %prog [options] ")
    optionparser.add_option("-f", "--query_vcf_file", dest="query_vcf_file",
                            help="query_vcf_file")
    optionparser.add_option("-s", "--short", action="store_true", default=False,
                            help="Produces a Short version for annotation only. ")

    
    (options, args) = optionparser.parse_args()
    if options.short:
        ext='_processed_04_05_11_short.vcf'
    else:
        ext='_processed_date.vcf'
        
    outfile=options.query_vcf_file.replace('.vcf',ext)
    #read_file_hp(options.query_vcf_file,outfile)
    read_file_hp2(options.query_vcf_file,outfile, options.short)
